# -*- coding: utf-8 -*-
import json
import logging
import threading
import subprocess
import sys
import signal
import os
import time

import requests
import serial
import re


g_runPidMap = {}

g_webGpsUrl = 'http://cg.visualdeep.com:18200/CityInspectors/sendGps.json'
g_webWifiUrl = 'http://cg.visualdeep.com:18200/CityInspectors/sendWifiProbe.json'

macId = 'HS001'
g_lastGPSData = {}

g_probeData = {}

# web.macId = macId

wifi_P = -50
wifi_N = 3


def startCpExec( func, deviceNum):
    os.chdir('../plate')
    res = subprocess.Popen(func, stdin=subprocess.PIPE,
                           stdout=subprocess.PIPE, shell=True, preexec_fn=os.setpgrp)
    os.chdir('../face')
    global g_runPidMap
    g_runPidMap[deviceNum] = res
    logging.error('推流执行进程 pid:'+str(res.pid))


def stopCP(deviceNum):
    resp = {}
    resp['code'] = '1'

    if g_runPidMap.has_key(deviceNum):
        try:
            resp['code'] = '1'
            proc = g_runPidMap[deviceNum]
            proc.terminate()
            proc.wait()
            os.killpg(proc.pid, signal.SIGTERM)
        except Exception as e:
            logging.error(e)
    else:
        resp['code'] = '0'

    return resp


def wifiprobe(data):

    global g_probeData
    global g_lastGPSData
    logging.error(data)
    g_probeData = json.loads(data)
    # print(g_lastGPSData)
    try:
        if g_lastGPSData.has_key('lat'):
            g_probeData['lat'] = g_lastGPSData['lat']
            g_probeData['lon'] = g_lastGPSData['lon']
        # logging.warn(g_lastGPSData)
        # g_probeData['macId'] = macId
        print("before recv data")
        # print(g_probeData[macId])
    except Exception, e:
        logging.error(e)
    return 'post'


def probeThreadStart(strs):
    indexflag = 0

    while True:
        indexflag = indexflag+1
        if indexflag % 6 == 0:

            try:
                global g_probeData
                senddata = g_probeData
                senddata['macId'] = macId

                inhttpRes = requests.post(g_webWifiUrl, json=senddata)
                logging.warn('发送WIFI探针请求后返回值:'+str(inhttpRes.text))
            except Exception, e:
                logging.error(e)
                logging.error('发送WIFI探针请求出错')
            indexflag = 0

        time.sleep(1)


def getGPSData():
    global g_lastGPSData
    return g_lastGPSData

class GpsParser:
    def __init__(self, port='/dev/ttyACM0', baudrate=9600, timeout=1):
        self.port = port
        self.baud = baudrate
        self.timeout = timeout
        self.GpsUart = serial.Serial(port, baudrate, timeout=timeout)
        self.GpsUart.flush()
        self.read()

    def messageType(self, message):
        checksum = self.checkDataSum(message)
        if checksum is False:
            return None
        if re.match(r'\$GPGGA', message):
            return 'GPGGA'
        elif re.match(r'\$GPRMC', message):
            return 'GPRMC'
        elif re.match(r'\$GNGGA', message):
            return 'GNGGA'

        return None

    def checkDataSum(self, message):
        payload = re.split(r'\*', message)

    def parseGPGGA(self, message):
        parsed_input = message.split(',')
        self.time = parsed_input[1]  # UTC time
        self.lat = parsed_input[2]
        self.lat_ns = parsed_input[3]
        self.lon = parsed_input[4]
        self.lon_ew = parsed_input[5]
        self.fix = parsed_input[6]
        self.sats = parsed_input[7]
        self.altitude = parsed_input[9]
        return self.current_values()

    def parseGNGGA(self, message):
        parsed_input = message.split(',')
        self.time = parsed_input[1]  # UTC time
        self.lat = parsed_input[2]
        self.lat_ns = parsed_input[3]
        self.lon = parsed_input[4]
        self.lon_ew = parsed_input[5]
        self.fix = parsed_input[6]
        self.sats = parsed_input[7]
        self.altitude = parsed_input[9]
        return self.current_values()

    def parseGPRMC(self, message):
        parsed_input = message.split(',')
        self.time = parsed_input[1]  # UTC time
        self.lat = parsed_input[3]
        self.lon = parsed_input[5]
        return self.current_values()

    def read(self):
        # '''
        # text = "$GPGGA,184353.07,1929.045,S,02410.506,E,1,04,2.6,100.00,M,-33.9,M,,0000*6D"
        # rawType = self.messageType(text)
        # if rawType is None:
        #     pass
        # elif rawType == 'GPGGA':
        #     return self.parseGPGGA(text)
        # elif rawType == 'GPRMC':
        #     return self.parseGPRMC(text)
        # '''

        while True:
            raw = self.GpsUart.readline()
            # print raw
            rawType = self.messageType(raw)

            if rawType is None:
                pass
            elif rawType == 'GPGGA':
                return self.parseGPGGA(raw)
            elif rawType == 'GNGGA':
                return self.parseGNGGA(raw)
            # elif rawType == 'GPRMC':
            #  	return self.parseGPRMC(raw)

    def current_values(self):
        data = {}
        data['time'] = self.time
        data['lat'] = self.lat
        data['lat_ns'] = self.lat_ns
        data['lon'] = self.lon
        data['lon_ew'] = self.lon_ew
        data['fix'] = self.fix
        data['sats'] = self.sats
        data['altitude'] = self.altitude

        return data


def gpsThreadStart(str):
    launchGps = GpsParser()
    indexflag = 0
    while True:

        indexflag = indexflag+1

        sendData = launchGps.read()
        # print(sendData)
        global g_lastGPSData
        g_lastGPSData = sendData
        if indexflag % 6 == 0:
            sendData['checkId'] = macId
            try:
                # data = json.dumps(sendData)
                inhttpRes = requests.post(g_webGpsUrl, json=sendData)
                print(inhttpRes)
                logging.info('发送GPS请求后返回值:'+str(inhttpRes.text))
            except Exception, e:
                logging.info(e)
                logging.info('发送GPS请求出错')
            print(sendData)
            indexflag = 0

        time.sleep(1)


# def wifiThreadStart(strs):
#     launchWifi = WifiParser()

#     indexflag = 0
#     while True:

#         indexflag = indexflag+1

#         sendData = launchWifi.read()
#         if indexflag % 6 == 0:
#             sendData['macid'] = macId
#             try:
#             	print("wifi send: ")
#                 print(sendData)
#                 inhttpRes = requests.post(g_webWifiUrl, json=sendData)
#                 logging.error('发送Wifi探针请求后返回值:'+str(inhttpRes.text))
#             except Exception, e:
#                 logging.error(e)
#                 logging.error('发送Wifi探针请求出错')
#             print(sendData)
#             indexflag = 0

#         time.sleep(1)


if __name__ == "__main__":
    gpsThread = threading.Thread(
        target=gpsThreadStart, name="gpsThreadStart", args=('',))
    gpsThread.start()

    #probeThread = threading.Thread(target=probeThreadStart, name="probeThreadStart", args=('',))
    # probeThread.setDaemon(True)
    # probeThread.start()

    # wifiThread = threading.Thread(
    #    target=wifiThreadStart, name="wifiThreadStart", args=('',))
    # wifiThread.start()
    app.run()
